﻿#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion

using System;
using System.Collections.Specialized;
using System.Globalization;
using System.Reflection;
using System.Security;
using System.Security.Principal;
using System.Threading;
using Newtonsoft.Utilities.Locator;
using Newtonsoft.Utilities.Time;
using Newtonsoft.Utilities.Reflection;
using System.Collections.Generic;

namespace Newtonsoft.Utilities.Logging
{
  public abstract class ExceptionFormatter
  {
    private static readonly IList<string> IgnoredProperties = new List<string> { "Source", "Message", "HelpLink", "InnerException", "StackTrace" };
    private readonly Exception _exception;
    private NameValueCollection _additionalInfo;

    protected ExceptionFormatter(Exception exception)
    {
      if (exception == null)
        throw new ArgumentNullException("exception");

      _exception = exception;
    }

    public NameValueCollection AdditionalInfo
    {
      get
      {
        if (_additionalInfo == null)
        {
          _additionalInfo = new NameValueCollection();
          _additionalInfo.Add("MachineName", GetMachineName());
          _additionalInfo.Add("TimeStamp", ServiceLocator.Clock.UtcDateTime().ToString(CultureInfo.CurrentCulture));
          _additionalInfo.Add("FullName", Assembly.GetExecutingAssembly().FullName);
          _additionalInfo.Add("AppDomainName", AppDomain.CurrentDomain.FriendlyName);
          _additionalInfo.Add("ThreadIdentity", Thread.CurrentPrincipal.Identity.Name);
          _additionalInfo.Add("WindowsIdentity", GetWindowsIdentity());
        }
        return _additionalInfo;
      }
    }

    public Exception Exception
    {
      get { return _exception; }
    }

    public virtual void Format()
    {
      WriteDescription();
      WriteDateTime(ServiceLocator.Clock.UtcDateTime());
      WriteException(_exception, null);
    }

    private static string GetMachineName()
    {
      try
      {
        return Environment.MachineName;
      }
      catch (SecurityException)
      {
        return "Permission Denied";
      }
    }

    private static string GetWindowsIdentity()
    {
      try
      {
        return WindowsIdentity.GetCurrent().Name;
      }
      catch (SecurityException)
      {
        return "Permission Denied";
      }
    }

    protected abstract void WriteAdditionalInfo(NameValueCollection additionalInformation);
    protected abstract void WriteDateTime(DateTime utcNow);
    protected abstract void WriteDescription();

    protected virtual void WriteException(Exception exceptionToFormat, Exception outerException)
    {
      if (exceptionToFormat == null)
      {
        throw new ArgumentNullException("exceptionToFormat");
      }
      WriteExceptionType(exceptionToFormat.GetType());
      WriteMessage(exceptionToFormat.Message);
      WriteSource(exceptionToFormat.Source);
      WriteHelpLink(exceptionToFormat.HelpLink);
      WriteReflectionInfo(exceptionToFormat);
      WriteStackTrace(exceptionToFormat.StackTrace);
      if (outerException == null)
      {
        WriteAdditionalInfo(AdditionalInfo);
      }
      Exception innerException = exceptionToFormat.InnerException;
      if (innerException != null)
      {
        WriteException(innerException, exceptionToFormat);
      }
    }

    protected abstract void WriteExceptionType(Type exceptionType);
    protected abstract void WriteHelpLink(string helpLink);
    protected abstract void WriteMessage(string message);
    protected abstract void WriteMemberInfo(MemberInfo memberInfo, object value);

    protected void WriteReflectionInfo(Exception exceptionToFormat)
    {
      if (exceptionToFormat == null)
        throw new ArgumentNullException("exceptionToFormat");

      Type type = exceptionToFormat.GetType();

      IList<MemberInfo> fieldsAndProperties = type.GetFieldsAndProperties(BindingFlags.Public | BindingFlags.Instance);

      foreach (MemberInfo memberInfo in fieldsAndProperties)
      {
        if (!IgnoredProperties.Contains(memberInfo.Name) && memberInfo.CanReadMemberValue() && !memberInfo.IsIndexedProperty())
        {
          object value;
          try
          {
            value = ReflectionUtils.GetMemberValue(memberInfo, exceptionToFormat);
          }
          catch (Exception)
          {
            value = "Access failed";
          }
          WriteMemberInfo(memberInfo, value);
        }
      }
    }

    protected abstract void WriteSource(string source);
    protected abstract void WriteStackTrace(string stackTrace);
  }
}